/*
 * @CreatDate: 2021-10-27 17:37:50
 * @Describe: 数字区间组件
 */

import './index.less';
import { useState, useEffect } from 'react';
import { Input, InputNumber } from 'antd';

const InputGroup = Input.Group;

const NumRange = ({
  value,
  onChange,
  precision,
  minProps,
  maxProps,
  ...rest
}) => {
  const [minNum, setMinNum] = useState(undefined);
  const [maxNum, setMaxNum] = useState(undefined);

  useEffect(() => {
    if (onChange) {
      onChange([minNum, maxNum]);
    }
  }, [minNum, maxNum]);

  useEffect(() => {
    const [outMin, outMax] = value || [];
    if (outMin !== minNum) {
      setMinNum(outMin);
    }
    if (outMax !== maxNum) {
      setMaxNum(outMax);
    }
  }, []);

  const onMinChange = v => {
    setMinNum(v);
  };

  const onMinBlur = e => {
    let v = e.target.value;
    if ((maxNum || maxNum === 0) && v > maxNum) {
      v = null;
      setMinNum(v);
    }
  };

  const onMaxChange = v => {
    setMaxNum(v);
  };

  const onMaxBlur = e => {
    let v = e.target.value;
    if ((minNum || minNum === 0) && v < minNum) {
      v = null;
      setMaxNum(v);
    }
  };

  return (
    <InputGroup compact {...rest} className="lycd-numRange">
      <InputNumber
        min={0}
        precision={precision}
        placeholder="请输入"
        value={minNum}
        onChange={onMinChange}
        onBlur={onMinBlur}
        className="left-item"
        {...minProps}
      />
      <Input className="middle" placeholder="~" disabled />
      <InputNumber
        className="right-item"
        min={0}
        precision={precision}
        placeholder="请输入"
        value={maxNum}
        onChange={onMaxChange}
        onBlur={onMaxBlur}
        {...maxProps}
      />
    </InputGroup>
  );
};

NumRange.defaultProps = {
  precision: 0,
  onChange: () => {},
};

export default NumRange;
